package com.huaxinzhi.print;

import static com.huaxinzhi.print.DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.huaxinzhi.print.databinding.ActivityPrintBinding;
import com.smasher.core.log.ToastUtil;
import com.smasher.core.other.WeakReferenceHandler;

public class PrintActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "PrintActivity";
    private ActivityPrintBinding mBinding;


    private PrintHelper mHelper;
    private WeakReferenceHandler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityPrintBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        mHelper = new PrintHelper();
        mHandler = new WeakReferenceHandler(mHelper);

        mBinding.Test1.setOnClickListener(this);
        mBinding.Test2.setOnClickListener(this);
        initBroadcast();
    }


    @Override
    protected void onStart() {
        super.onStart();
        //获取连接对象是否连接
        DeviceConnFactoryManager[] deviceConnFactoryManagers;
        deviceConnFactoryManagers = DeviceConnFactoryManager.getDeviceConnFactoryManagers();
        for (int i = 0; i < 4; i++) {
            if (deviceConnFactoryManagers[i] != null && deviceConnFactoryManagers[i].getConnState()) {
                mBinding.state.setText(getString(R.string.str_conn_state_connected) + "\n" + mHelper.getConnDeviceInfo());
                break;
            } else {
                mBinding.state.setText(getString(R.string.str_conn_state_disconnect));
            }
        }
    }

    /**
     * 注册广播
     * Registration broadcast
     */
    private void initBroadcast() {
        IntentFilter filter = new IntentFilter();//USB访问权限广播
        filter.addAction(ACTION_QUERY_PRINTER_STATE);//查询打印机缓冲区状态广播，用于一票一控
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);//与打印机连接状态
        registerReceiver(receiver, filter);
    }


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                //连接状态
                case DeviceConnFactoryManager.ACTION_CONN_STATE:
                    int state = intent.getIntExtra(DeviceConnFactoryManager.STATE, -1);
                    int deviceId = intent.getIntExtra(DeviceConnFactoryManager.DEVICE_ID, -1);
                    switch (state) {
                        case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:

                            if (mHelper.getId() == deviceId) {
                                Log.e(TAG, "connection is lost");
                                mBinding.state.setText(getString(R.string.str_conn_state_disconnect));
                            }
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTING:
                            mBinding.state.setText(getString(R.string.str_conn_state_connecting));
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                            mBinding.state.setText(getString(R.string.str_conn_state_connected) + "\n" + mHelper.getConnDeviceInfo());
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_FAILED:
                            ToastUtil.info(context, getString(R.string.str_conn_fail));
                            //wificonn=false;
                            mBinding.state.setText(getString(R.string.str_conn_state_disconnect));
                            break;
                        default:
                            break;
                    }
                    break;
                //连续打印，一票一控，防止打印机乱码
                case ACTION_QUERY_PRINTER_STATE:
                    mHelper.print();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 提示
     *
     * @param msg
     */
    private void tip(String msg) {
        Message message = new Message();
        message.obj = msg;
        message.what = Constant.tip;
        mHandler.sendMessage(message);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy()");
        unregisterReceiver(receiver);
        if (mHelper != null) {
            mHelper.close();
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.Test1) {
            mHelper.serialConnectOri(9600, "/dev/ttyXRM0");
        } else if (id == R.id.Test2) {
            mHelper.btnLabelPrint(null);
        }
    }
}